import config from '../config';
import _ from 'lodash';


define(function(require, exports, module) {
    var angular = require('angular');
    require("@yunke/jquery_pagination");
    require('angular-ui');
    require('../common/nav');
    require("../../plugins/select2/select2");
    require('../abnormal/abnormal-common');
    require("uploader");
    var util = require('@yunke/core/util').default;
    var ui = require("@yunke/core/ui");

    var moment = require('moment');

    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var orgapi_prefix = G_CONFIG["orgapi_prefix"]; //api前缀
    angular.module('SpecialAuthorize', ['ngUI', 'myNav', 'select2', 'AbnormalCommonService'])
            .controller('specialAuthorizeListCtrl', ['$scope', 'abnormalCommonService', 'appservice', function($scope, abnormalCommonService, appservice) {
            appservice.name = '明源云客-特批授权';
                    ui.loading('', '正在加载…');
                    $scope.authorizes = [];
                    $scope.sn = 0;
                    $scope.filterDataCities = [{
                            areaName: '全部', selected: true, areaId: ''
                        }];
                    //获取合同区域列表
                    abnormalCommonService.getContractAreas(function(data) {
                        $.merge($scope.filterDataCities, data);
                        $scope.$applyAsync();
                    });

                    $scope.changeCity = function(city) {
                        $scope.query.execute();
                    }
                    $scope.filterFulfils = [{
                            name: '全部', selected: true, value: ''
                        }, {
                            name: '是', value: '1'
                        }, {
                            name: '否', value: '0'
                        }];


                    $scope.changeFulfil = function(fulfil) {
                        $scope.query.execute();
                    }

                    //查询条件
                    $scope.query = {
                        keyword: '',
                        execute: function(page) {
                            var parms = {keyword: this.keyword};
                            parms.pageIndex = page || 1;
                            parms.pageSize = config.pager().pageSize;
                            parms.sortBy = 'created_on';
                            parms.sortAsc = 'false';

                            //收集过滤条件
                            var filterCity = $.grep($scope.filterDataCities, function(o, n) {
                                return o.selected == true;
                            })
                            if (filterCity.length) {
                                parms.areaId = filterCity[0].areaId;
                            }

                            var filterFulfil = $.grep($scope.filterFulfils, function(o, n) {
                                return o.selected == true;
                            })
                            if (filterFulfil.length) {
                                parms.fulfil = filterFulfil[0].value;
                            }

                            util.myAjax({
                                url: orgapi_prefix + "/special-authorize/get-list",
                                type: "GET",
                                cache: false,
                                data: parms,
                                context: this,
                                success: function(json) {
                                    if (+json.retCode === 0) {
                                         // 特批类型
                                        const categoryList = $scope.getCategoryList();

                                        _.each(json.data.items, item => {
                                            const found = _.find(categoryList, category => +category.id === +item.category);
                                            if (found) {
                                                item.categoryName = found.value;
                                            }
                                        });

                                        $scope.authorizes = json.data.items;

                                        $scope.$applyAsync();

                                        $scope.startPageIndex = (parms.pageIndex - 1) * 10;

                                        $('#pagination')
                                            .pagination(json.data.total, {
                                                current_page: parms.pageIndex - 1,
                                                num_edge_entries: 1,
                                                num_display_entries: 4,
                                                callback: function(page_index) {
                                                    $scope.$apply(() => {
                                                        $scope.startPageIndex = (page_index - 1)*10;
                                                        $scope.query.execute(page_index);
                                                    })
                                                },
                                                items_per_page: config.pager().pageSize
                                            });

                                    } else {
                                        util.alert(json.errMsg);
                                    }
                                },
                                complete: function() {
                                    ui.removeLoading();
                                }
                            });

                        }
                    };

                    $scope.saveAuthorize = function(dialog, dialogScope) {
                        //todo：此发票已存在特批
                        return util.myAjax({
                            url: orgapi_prefix + "/special-authorize/save",
                            type: "POST",
                            dataType: 'json',
                            cache: false,
                            data: _.cloneDeep(_.omit(dialogScope.data, ['ddlConfigOrganization', 'ddlConfigContract', 'ddlConfigPrinciple', 'delAttachment', 'changeCategory'])),
                            context: this,
                            success: function(json) {
                                if (+json.retCode === 0) {
                                    dialogScope.data.ContractId = json.data;
                                    util.alert('保存成功');
                                } else {
                                    util.alert(json.errMsg);
                                }
                            },
                            complete: function() {
                                ui.removeLoading();
                                $scope.query.execute();
                            }
                        });
                    };

                    $scope.getEmptyAuthorize = function(dialogScope) {
                        return {
                            categoryList: $scope.getCategoryList(),
                            attachment: [],
                            ddlConfigOrganization: {
                                allowClear: false,
                                placeholder: '',
                                ajax: {
                                    url: orgapi_prefix + "/organization/get-organization-list-for-select2",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                onchange2: function(newVal) {
                                    dialogScope.data.FriendlyName = newVal.text;
                                },
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                }
                            },
                        ddlConfigContract: {
                            allowClear: false,
                            placeholder: '',
                            ajax: {
                                url: api_prefix + "/contract/get-contract-list-for-sepcial-authorize-select2",
                                dataType: 'json',
                                delay: 250,
                                data: function(term, page) {
                                    return {
                                        keyword: term,
                                        orgId:dialogScope.data.OrganizationId,
                                        limit:10
                                    };
                                },
                                results: function(data, page) {
                                    return {
                                        results: data.data
                                    };
                                },
                                cache: true
                            },
                            escapeMarkup: function(markup) {
                                return markup;
                            },
                            minimumInputLength: 1,
                            open: function () {
                                alert();
                            },
                            templateResult: function (data) {
                                return data;
                            },
                            templateSelection: function (data) {
                                return data;
                            }
                        },
                            ddlConfigPrinciple: {
                            ajax: {
                                    url: api_prefix + "/erp-interface/get-users",
                                    dataType: 'json',
                                    delay: 250,
                                    data: function(term, page) {
                                        return {
                                            keyword: term,
                                            limit: 10
                                        };
                                    },
                                    results: function(data, page) {
                                        return {
                                            results: data.data
                                        };
                                    },
                                    cache: true
                                },
                                escapeMarkup: function(markup) {
                                    return markup;
                                },
                                minimumInputLength: 1,
                                templateResult: function(data) {
                                    return data;
                                },
                                templateSelection: function(data) {
                                    return data;
                                },
                                onchange2: function(newVal){
                                    dialogScope.data.principalName = newVal.text;
                                }
                            },
                            delAttachment: function(data, id) {
                                $(data.attachment).each(function(idx, item) {
                                    if (item.document_id.toLowerCase() == id.toLowerCase()) {
                                        data.attachment.splice(idx, 1);
                                    }
                                });
                            },
                            changeCategory: function(data) {
                                if (typeof (data) == 'undefined') {
                                    return;
                                }
                                data.category_temp = data.category;
                            }
                        };
                    };
                    //确定并新增
                    var addAndSaveBtn = function($dialog,$dialogScope){
                        $($dialog.node).find('[i-id=okAdd]').on('click',function(){
                            $dialogScope.saveAndAdd = true;
                            $($dialog.node).find('[i-id=ok]').trigger('click');
                            //保存上一次新增值
                            $scope.lastAddAuthorize = $dialogScope.data;
                        });
                        $($dialog.node).find('[i-id=cancel]').on('click',function(){
                            $dialogScope.saveAndAdd = false;
                            $scope.ifLastAddNewAuthorize = false;

                        });
                        $($dialog.node).find('[i-id=ok]').on('click',function(){
                            $scope.ifLastAddNewAuthorize = false;
                        });
                    };
                    $scope.onCloseAuthorize = function($dialogScope){
                        if($dialogScope.saveAndAdd === true){
                            $('#addAuthorizeButton').trigger('click');
                            $scope.ifLastAddNewAuthorize = true;
                        }
                    };

                    $scope.onAuthorizeEditShow = function(row, dialog, dialogScope) {
                        ui.loading('', '正在加载…');

                        addAndSaveBtn(dialog, dialogScope);

                        dialogScope.data = $scope.getEmptyAuthorize(dialogScope);
                        // 编辑模式
                        util.myAjax({
                            url: orgapi_prefix + "/special-authorize/get-detail",
                            type: "GET",
                            cache: false,
                            data: {ContractId: row.ContractId},
                            context: this,
                            success: function(json) {
                                if (+json.retCode === 0) {
                                    for (const attr in json.data) {
                                        dialogScope.data[attr] = json.data[attr];
                                    }

                                    const promiseDate = moment(dialogScope.data['promiseFulfilTime'],'YYYY-MM-DD HH:mm:ss');
                                    if(promiseDate.isValid()){
                                        dialogScope.data['promiseFulfilTime'] = promiseDate.format('YYYY-MM-DD');
                                    }
                                    const actualDate = moment(dialogScope.data['actualFulfilTime'],'YYYY-MM-DD HH:mm:ss');
                                    if(actualDate.isValid()){
                                        dialogScope.data['actualFulfilTime'] = actualDate.format('YYYY-MM-DD');
                                    }

                                    dialogScope.data.category_temp = dialogScope.data.category;
                                    dialogScope.data.attachment = json.data['attachment'];

                                    $('#organization_id').data('select2').updateSelection({id: dialogScope.data['UniqueName'], text: dialogScope.data['FriendlyName']});
                                    $('#contract_code').data('select2').updateSelection({id: dialogScope.data['ContractNum'], text: dialogScope.data['ContractNum']});
                                    $('#promise_fulfil_principle').data('select2').updateSelection({id: dialogScope.data['promiseFulfilPrinciple'], text: dialogScope.data['principalName']});

                                } else {
                                    util.alert(json.errMsg);
                                }
                            },
                            complete: function() {
                                dialogScope.$applyAsync();
                                ui.removeLoading();
                            }
                        });

                        // 上传控件初始化
                        $('#fileupload').fileupload({
                            dataType: 'json',
                            url: api_prefix + "/common/file/upload-document",

                            add: function(e, data) {
                                // 大小限制
                                if(data.files.length>0){
                                    if(data.files[0].size>config.uploader.max_file_size){
                                        util.alert('文件大小超出'+config.uploader.max_file_size_text+'，无法上传。');
                                        return;
                                    }
                                }
                                data.submit();
                                ui.loading('', '正在上传…');
                                $("#fileupload_error").hide();
                            },
                            done: function(e, data) {
                                var res = data.result;
                                if (res.retCode == "0") {
                                    var document = {
                                        document_id: ++$scope.sn,
                                        document_name: data.files[0].name,
                                        document_ext_name: '',
                                        document_path: res.data.path,
                                        business_id: ''
                                    };
                                    dialogScope.data.attachment.push(document);
                                    dialogScope.$applyAsync();

                                    $("#fileupload_error").html("");
                                    $("#fileupload_error").hide();
                                } else {
                                    $("#fileupload_error").html("上传失败:" + res.errMsg);
                                    $("#fileupload_error").show();
                                }
                            },
                            fail: function(e, data) {
                                $("#fileupload_error").html("上传失败:" + data.errorThrown);
                                $("#fileupload_error").show();
                            },
                            always: function(e, data) {
                                ui.removeLoading();
                            }
                        });

                    }

                    $scope.getCategoryList = function() {
                        return [
                            {id: 1, value: '合同未归档'},
                            {id: 2, value: '款项未回'},
                            {id: 3, value: '合同未归档且款项未回'},
                            {id: 4, value: '结算款未支付'},
                            {id: 5, value: '合同扫描件未提供'},
                            {id: 6, value: '合同扫描件未提供且结算款未支付'}
                        ];
                    };

                    $scope.query.execute();
                }]);
});
